package org.example.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.ByteArrayInputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.apache.poi.xwpf.usermodel.*;
import org.example.pojo.Asset;
import org.example.service.ExportService;
import org.example.utils.QRCodeGenerator;
import org.example.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.spring5.SpringTemplateEngine;


@RestController
@RequestMapping("/export")
public class ExportController {

    @Autowired
    private ExportService exportService;

    @GetMapping("/word")
    public ResponseEntity<byte[]> exportWord() throws Exception {
        // 调用服务生成 Word 二进制流
        byte[] wordBytes = exportService.generateWord();
        // 构建响应头（强制下载）
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "export.docx");
        // 响应文件
        return new ResponseEntity<>(wordBytes, headers, HttpStatus.OK);
    }

    @GetMapping("/word2")
    public void exportWord2(HttpServletResponse response) throws Exception {
        // 1. 获取资产数据（含二维码）
        List<Asset> assets = getAssets();

        // 2. Freemarker 渲染模板
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setClassForTemplateLoading(this.getClass(), "/templates");
        cfg.setDefaultEncoding("UTF-8");
        Template template = cfg.getTemplate("word.ftl");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename=export.docx");

        Writer out = new OutputStreamWriter(response.getOutputStream());
        Map<String, Object> model = new HashMap<>();
        model.put("assets", assets);
        template.process(model, out);
        out.flush();
//        Map<String, Object> model = new HashMap<>();
//        model.put("assets", assets);
////        String xmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
//        StringWriter writer = new StringWriter();
//        template.process(model, writer);
//
//        XWPFDocument document = new XWPFDocument(
//                new ByteArrayInputStream(writer.toString().getBytes()));
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        response.setHeader("Content-Disposition", "attachment; filename=export.docx");
//        document.write(response.getOutputStream());
//        document.close();
        // 3. POI 构建 Word 文档
//        XWPFDocument document = new XWPFDocument();
//        XWPFParagraph paragraph = document.createParagraph();
//        XWPFRun run = paragraph.createRun();
//        run.setText(htmlContent); // 插入 HTML 内容
//        run.setFontSize(12); // 字体大小
//        run.setFontFamily("宋体"); // 字体
        // 2. 生成Word文档
//        XWPFDocument document = new XWPFDocument(
//                new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
        // 4. 输出文件
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        response.setHeader("Content-Disposition", "attachment; filename=tool.docx");
//        document.write(response.getOutputStream());
//        document.close();
    }

    public List<Asset> getAssets() {
        List<Asset> assets = new ArrayList<>();
        assets.add(new Asset("017080000000000005418996", "输电运检中心输电带电一班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051297", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846653", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051303", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846660", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000005418996", "输电运检中心输电带电一班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051297", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846653", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051303", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846660", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000005418996", "输电运检中心输电带电一班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051297", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846653", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        assets.add(new Asset("0170800000000000051303", "汤阴变安全工器具室", "国网安阳供电公司-变电运维中心", "安全带-半身式,z-坠落悬挂"));
        assets.add(new Asset("017080000000000004846660", "输电运检中心输电检修二班工器具室", "国网商丘供电公司-输电运检中心", "安全带-全身式,z-坠落悬挂"));
        // 为每个资产生成二维码 Base64 字符串
        assets.forEach(asset -> asset.setQrCodeBase64(QRCodeUtil.generateQRCodeBase64(asset.getId())));

        return assets;
    }
}